//
//  FBDUpload.m
//  AVPlayerTest
//
//  Created by feng on 16/9/27.
//  Copyright © 2016年 冯宝东. All rights reserved.
//
/**   下面是类功能注释说明  联系人：冯宝东 QQ : 347428774 备注ios
 *
 *
 *
 *
 *
 *
 **/
#define MAXVersion  80000
#import "FBDUpload.h"

@implementation FBDUpload
{
    NSString*_remotePath;

}
/**
 用路径初始化上传对象
 
 @param filePath 文件路径
 
 @return 上传对象
 */
-(instancetype)initWithUploadFilePath:(NSString*)filePath withMIME:(NSString*)MIME remotePath:(NSString*)remotePath
{
    self=[super init];
    if (self) {
        _remotePath=remotePath;
        [self configeUpLoadSettingWithMIME:MIME file:filePath];
    }
    
    return self;
}

/**
 用二进制初始化上传对象
 
 @param fileData 二进制
 
 @return 上传对象
 */
-(instancetype)initWithUploadFileData:(NSData*)fileData withMIME:(NSString*)MIME remotePath:(NSString*)remotePath
{
    self=[super init];
    if (self) {
        _remotePath=remotePath;
        [self configeUpLoadSettingWithMIME:MIME file:fileData];
    }
    
    return self;
}
-(void)configeUpLoadSettingWithMIME:(NSString*)MIME file:(id)file
{
//    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://jsonplaceholder.typicode.com/posts"]];
//                                                                         [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    //这一行一定不能少，因为后面是转换成JSON发送的
//                                                                         [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
//                                                                         [request setHTTPMethod:@"POST"];
//                                                                         [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
//                                                                         [request setTimeoutInterval:20];
//                                                                         NSDictionary * dataToUploaddic = @{@"fengbaodong":@"name"};
//                                                                         NSData * data = [NSJSONSerialization dataWithJSONObject:dataToUploaddic
//                                                                                                                         options:NSJSONWritingPrettyPrinted
//                                                                                                                           error:nil];
//                                                                         NSURLSessionUploadTask * uploadtask = [self.session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//        if (!error) {
//            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//            self.responselabel.text = dictionary.description;
//        }else{
//            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@Error message:error.localizedFailureReason preferredStyle:UIAlertControllerStyleAlert];
//            [alert addAction:[UIAlertAction actionWithTitle:@OK style:UIAlertActionStyleCancel handler:nil]];
//            [self presentViewController:alert animated:YES completion:nil];
//        }
//        
//    }];
//   [uploadtask resume];

//    _remotePath;
    NSMutableURLRequest * request = [NSMutableURLRequest
                                     requestWithURL:[NSURL URLWithString:@"http://www.freeimagehosting.net/upload.php"]];
    [request addValue:@"img" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"ation/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPMethod:@"POST"];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval:20];
    NSData *fileData=nil;
    if ([file isKindOfClass:[NSString class]])
    {
        fileData=[NSData dataWithContentsOfFile:file];
        
    }else if([file isKindOfClass:[NSData class]])
    {
        fileData=file;
        
    }
    
    if (fileData==nil)
    {
        
        NSLog(@"data is nil  请检查路径或者数据的正确性");
        return;
    }
    
    
    NSURLSessionConfiguration *cfg=[NSURLSessionConfiguration defaultSessionConfiguration];
    self.session=[NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionUploadTask * uploadtask = [self.session uploadTaskWithRequest:request fromData:fileData];
    [uploadtask resume];

    /*
     
     completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
     NSString * htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     NSLog(@"%@",htmlString);
     
     }
     */
    
}


- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error
{

    NSLog(@">>>>>>>>%@",task.response);
    
    

}


-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
  didSendBodyData:(int64_t)bytesSent
   totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    
#if (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0)
    // 获得上传进度
    float progress = (double)totalBytesSent / totalBytesExpectedToSend;
    NSLog(@"upload progress is %.2f",progress);
#endif
    
    
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data
{

    NSString * htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",htmlString);

}



@end
